package CanvaWeb.CanvaWeb.WebSocket;

import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;


public class MyWebSocketHandler extends TextWebSocketHandler {

    private final List<WebSocketSession> sessions = new CopyOnWriteArrayList<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 使用 `@PathVariable` 获取 roomId
        String uri = session.getUri().toString();
        String roomId = uri.substring(uri.lastIndexOf("/") + 1); // 获取路径中的最后部分作为 roomId
        Long roomIdLong = Long.parseLong(roomId); // 转换为 Long 类型

        // 将新连接添加到 sessions 列表
        sessions.add(session);

        // 输出连接的房间 ID
        System.out.println("Connected to room: " + roomIdLong);

        // 可以在这里进行其他与连接相关的处理
    }

    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String payload = message.getPayload();
        System.out.println("Received message: " + message.getPayload());

        for (WebSocketSession s : sessions) {
            if (s.isOpen()) {
                s.sendMessage(new TextMessage(payload)); // 向所有连接的客户端推送消息
                System.out.println("Sent message to session: " + s.getId());
            }
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        sessions.remove(session);
        System.out.println("Disconnected from room.");
    }
}




